<?php

//require_once dirname(__FILE__) . '/../protected/extensions/PHPMailer/class.phpmailer.php';

function pr($arr, $die = true) {
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
    if ($die) {
        die();
    }
}

function dump($arr, $die = true) {
    echo "<pre>";
    var_dump($arr);
    echo "</pre>";
    if ($die) {
        die();
    }
}

function read($var) {
    if (isset($var)) {
        $returnVar = $var;
    } else {
        $returnVar = NULL;
    }
    return $var;
}

function writeToFile($arr) {
    $str = "<pre>";
    $str.=print_r($arr, true);
    $str.="</pre>";

    $fp = fopen('file.txt', 'a');
    fwrite($fp, $str);
    fclose($fp);
}

function printMsg($msg) {
    echo $msg . "\n";
}

function guid() {

    if (function_exists('com_create_guid')) {
        $guid = com_create_guid();
        $guid = preg_replace("/[^A-Za-z0-9]/", "", $guid);
        return $guid;
    } else {
        mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $guid = substr($charid, 0, 8)
                . substr($charid, 8, 4)
                . substr($charid, 12, 4)
                . substr($charid, 16, 4)
                . substr($charid, 20, 12);
        return $guid;
    }
}

function createThumb($path, $width, $height, $resize = true) {
    Yii::import("ext.phpthumb.EasyPhpThumb");
    ini_set('upload_max_filesize', '10M');
    ini_set('max_execution_time', '1800');

    $thumbs = new EasyPhpThumb();
    $thumbs->init();

    $thumbs->setThumbsDirectory(aqConfig::getUploadDir());
    if ($resize) {
        $thumbs->load($path)
                ->resize($width, $height);
        return $thumbs->save();
    } else {
        $thumbs->load($path);
        return $thumbs->save();
    }
}

function addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

function changePassword($obj, $post) {
    if (isset($post)) {
        $obj->setAttribute('password', md5($post));
        $obj->save(false); // save the change to database
    }
}
//
//function populateEmailTemplate($msgTpl, array $params = NULL) {
//
//    if ($msgTpl != '') {
//        $msgTpl = Yii::getPathOfAlias('webroot') . '/protected/views/email/' . $msgTpl;
//    }
//
//    $body = '';
//    if (file_exists($msgTpl)) {
//        $body = file_get_contents($msgTpl);
//        if (!empty($params)) {
//            foreach ($params as $k => $v)
//                $body = str_replace($k, $v, $body);
//        }
//    }
//    return $body;
//}
//
//function anotherEmailSend($to, $subject, $body) {
//
//    try {
//        $mail = new PHPMailer(true);
//        $mail->IsSMTP();
//        $mail->Host = EMAIL_HOST;
//        $mail->SMTPAuth = EMAIL_SMTP_AUTH;
//        $mail->Username = EMAIL_USER_NAME;
//        $mail->Password = EMAIL_PASSWORD;
//        $mail->SetFrom(EMAIL_FROM, 'Why Wait');
//        $mail->Subject = $subject;
//        $mail->MsgHTML($body);
//        $mail->IsHTML(true); // send as HTML
//        $mail->AddAddress($to);
//        $mail->Send();
//    } catch (Exception $e) {
//        
//    }
//}
//
//function emailSend($name, $userName, $password, $msgTpl = null) {
//    try {
//        $mail = new PHPMailer(true);
//
//        $mail->IsSMTP();
//        $mail->Host = EMAIL_HOST;
//        $mail->SMTPAuth = EMAIL_SMTP_AUTH;
//        $mail->Username = EMAIL_USER_NAME;
//        $mail->Password = EMAIL_PASSWORD;
//        $mail->SetFrom(EMAIL_FROM, 'Why Wait');
//        $mail->Subject = 'Your password was updated';
//        if ($msgTpl && file_exists($msgTpl)) {
//            $msgTpl = Yii::getPathOfAlias('webroot') . '/protected/views/email/' . $msgTpl;
//        } else {
//            $msgTpl = Yii::getPathOfAlias('webroot') . '/protected/views/email/restaurantChangePassword.php';
//        }
//        $body = '';
//        if (file_exists($msgTpl)) {
//            $body = file_get_contents($msgTpl);
//            $body = str_replace("NAME", $name, $body);
//            $body = str_replace("EMAIL", $userName, $body);
//            $body = str_replace("PASSWORD", $password, $body);
//        }
//
//        $mail->MsgHTML($body);
//        $mail->IsHTML(true); // send as HTML
//        $mail->AddAddress($userName);
//        $mail->Send();
//    } catch (Exception $e) {
//        
//    }
//}
//
//function forgatePasswordEmail($userName, $user, $activationLink, $subject, $msgTpl) {
//    try {
//
//        $mail = new PHPMailer(true);
//
//        $mail->IsSMTP();
//        $mail->Host = EMAIL_HOST;
//        $mail->SMTPAuth = EMAIL_SMTP_AUTH;
//        $mail->Username = EMAIL_USER_NAME;
//        $mail->Password = EMAIL_PASSWORD;
//        $mail->SetFrom(EMAIL_FROM, 'Why Wait');
//        $mail->Subject = $subject;
//        $msgTpl = Yii::getPathOfAlias('webroot') . '/protected/views/email/' . $msgTpl;
//        // $body = $activationKey;
//        $body = '';
//        if (file_exists($msgTpl)) {
//            $body = file_get_contents($msgTpl);
//            $body = str_replace("ACTIVATIONLINK", $activationLink, $body);
//            $body = str_replace('$RESTAURANT_NAME', $user->username, $body);
//        }
//
//        $mail->MsgHTML($body);
//        $mail->IsHTML(true); // send as HTML
//        $mail->AddAddress($userName);
//        $mail->Send();
//    } catch (Exception $e) {
//        
//    }
//}

function dateTime($date, $dateFormate = 'm-d-Y', $isTime = true, $isAmPm = true, $_12HoursClock = false) {

    $time = "";
    if ($isTime) {
        if ($_12HoursClock) {
            $time = " h:i:s";
        } else {
            $time = " H:i:s";
        }

        if ($isAmPm) {
            $time .= " a";
        }
    }

    $dateFormate = $dateFormate . $time;

    $date = strtotime(str_replace('-', '/', $date));

    if (!empty($date)) {
        return $date = date($dateFormate, $date);
    }

    return NULL;
}

function dateTimeDeal($date, $dateFormate = 'm-d-Y') {
    return $date = date($dateFormate, strtotime(str_replace('-', '/', $date)));
}

function getReviewRating($id, $is_active = FALSE) {
    $command = Yii::app()->db->createCommand();
    $subSql = '';
    $conditions = array(':id' => $id);

    if ($is_active) {
        $subSql = 'AND is_admin_approved=:is_admin_approved';
        $conditions = array(':id' => $id, ':is_admin_approved' => 1);
    }
    $sql = 'SELECT rating FROM `review` WHERE id=:id ' . $subSql;
    $rating = $command->setText($sql)
            ->queryScalar($conditions);
    return $rating = calculateRating($rating);
}

function getRating($id, $is_active = FALSE) {
    $command = Yii::app()->db->createCommand();

    $subSql = '';
    $conditions = array(':id' => $id);

    if ($is_active) {
        $subSql = 'AND is_active=:is_active';
        $conditions = array(':id' => $id, ':is_active' => 1);
    }

    $rating = $command->setText('SELECT `rating_sum` / `rating_count` AS rating FROM `restaurant` WHERE id=:id ' . $subSql)
            ->queryScalar($conditions);

    return $rating = calculateRating($rating);
}

function calculateRating($rating) {
    if ($rating != null) {
        if ($rating >= MAX_RATING) {
            $rating = 5;
        } elseif ($rating <= MIN_RATING) {
            $rating = 0;
        }
        $constent = (int) $rating;
        $remainder = $rating - $constent;
        if ($remainder != 0) {
            if ($remainder < RATING_MIN_LIMIT) {
                $rem = 0.00;
            } elseif ($remainder >= RATING_MAX_LIMIT) {
                $rem = 1.00;
            } else {

                $rem = 0.5;
            }
            $rating = $constent + $rem;
        }

        return number_format($rating, 2, '.', '');
    }
}

function showRating($rating) {

    $string = '';
    $count = (int) $rating;
    $rem = $rating - $count;
    for ($i = 0; $i < MAX_RATING; $i++) {
        if ($i < $count) {
            $img = 'full.png';
        } elseif ($rem != 0) {
            $img = 'half.png';
            $rem = 0;
        } else {
            $img = 'blank.png';
        }

        $string.='<img src="' . Yii::app()->getBaseUrl() . '/images/' . $img . '">';
    }

    return $string;
}

function getExpireTime() {
    //    $increase_time = (int) X_AUTHKEY_INCREASE_EXPIRE_TIME;
    //    $calculate_time =(int) 60 * $increase_time;
    //    $expires_on = time() + $calculate_time;
    $expires_on = strtotime('1-1-2038');
    return $expires_on;
}

function updateExexpireTime($auth_key) {
    $auth = getAuthKeyObj($auth_key);
    if ($auth) {
        $auth_key = $auth->getAttribute('auth_key');
        $expires_on = getExpireTime();
        $auth->setAttribute('expires_on', $expires_on);
        $auth->update();
    }
}

function getAuthKeyObj($auth_key) {
    $expires_on = time();
    $auth_key_obj = AuthKey::model()->find('auth_key=:auth_key AND expires_on >=:expires_on', array(':auth_key' => $auth_key, ':expires_on' => $expires_on));
    return $auth_key_obj;
}

function getLatLongByAddress($address) {
    $delay = 0;
    $lat = '';
    $lng = '';
    $base_url = "http://" . MAPS_HOST . "/maps/geo?output=csv&key=" . KEY;

    $request_url = $base_url . "&q=" . urlencode($address);

    $csv = file_get_contents($request_url) or die("url not loading");
    $csvSplit = explode(",", $csv);
    $status = $csvSplit[0];

    if (strcmp($status, "200") == 0) {
        // successful geocode
        $geocode_pending = false;
        $lat = $csvSplit[2];
        $lng = $csvSplit[3];
    } else if (strcmp($status, "620") == 0) {
        // sent geocodes too fast
        $delay += 100000;
    } else {
        // failure to geocode
        $geocode_pending = false;
        "Address " . $address . " failed to geocoded. ";
        "Received status " . $status . "
		\n";
        usleep($delay);
    }

    return array('lat' => $lat, 'long' => $lng);
}

function clickInfo($id, $checkInto) {
    return $row = Yii::app()->db->createCommand(array(
        'select' => array('*,count(' . $checkInto . ')'),
        'from' => 'trk_restaurant_check_in',
        'where' => 'id=:' . $id,
    ))->queryRow();
}

function ajaxDilogBox($controller, $dilogBoxId, $msg, $title = '') {
    $controller->beginWidget('zii.widgets.jui.CJuiDialog', array(
        'id' => $dilogBoxId,
        'options' => array(
            'title' => $title,
            'width' => 400,
            'height' => 200,
            'autoOpen' => false,
            'resizable' => false,
            'modal' => true,
            'buttons' => array(
                ///'OK' => 'js:function(){alert("OK");}',
                'OK' => 'js:function(){$(this).dialog("close");}',
            ),
        ),
    ));
    echo $msg;
    $controller->endWidget('zii.widgets.jui.CJuiDialog');
}

function yiiUserLogOut() {
    //We logout for last session value
    Yii::app()->user->logout();
    Yii::app()->user->clearStates();
    $session = new CHttpSession;
    $session->destroy();
}

function calculateDistance($in_lat, $in_long) {
    /*
     *   Haversine formula:
      a = sin�(?lat/2) + cos(lat1).cos(lat2).sin�(?long/2)
      c = 2.atan2(va, v(1-a))
      d = R.c
     * From http://www.movable-type.co.uk/scripts/latlong.html
     */


    $lat1 = $in_lat;
    $lon1 = $in_long;
    $lat2 = $this->latitude;
    $lon2 = $this->longitude;
    $R = EARTH_RADIUS;

    $dLat = $lat2 - $lat1;
    $dLat = deg2rad($dLat);
    $dLon = $lon2 - $lon1;
    $dLon = deg2rad($dLon);

    $lat1 = deg2rad($lat1);
    $lat2 = deg2rad($lat2);
    $a = sin($dLat / 2) * sin($dLat / 2) + sin($dLon / 2) * sin($dLon / 2) * cos($lat1) * cos($lat2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $distance = $R * $c;
    return $distance;
}

function uploadRestaurantImages($obj, $url, $uploadPath, $imageId, $displayImageUrl) {

    $obj->widget('ext.EAjaxUpload.EAjaxUpload', array(
        'id' => $imageId . uniqid(),
        'config' => array(
            'action' => $url,
            'allowedExtensions' => array("jpg", "jpeg", "gif", "png"), //and etc...
            'sizeLimit' => IMAGESIZE, // maximum file size in bytes
            'minSizeLimit' => 1, // minimum file size in bytes image_border
            'onComplete' => "js:function(id, fileName, responseJSON){
					//  alert(responseJSON.errorMsg);
					$('.qq-upload-file').attr('style','display:none')
					$('.qq-upload-size').attr('style','display:none')
					$('.qq-upload-list').attr('style','list-style:none')
					$('#restaurant_dispaly_images').load('" . $displayImageUrl . "');
					//$('.image_border').attr('src','" . $uploadPath . "'+fileName)



}",
            'messages' => array(
                'typeError' => "{file} has invalid extension. Only {extensions} are allowed.",
                'sizeError' => "{file} is too large, maximum file size is {sizeLimit}.",
                'minSizeError' => "{file} is too small, minimum file size is {minSizeLimit}.",
                'emptyError' => "{file} is empty, please select files again without it.",
                'onLeave' => "The files are being uploaded, if you leave now the upload will be cancelled."
            ),
            'showMessage' => "js:function(message){ alert(message); }"
        )
    ));
}

function addButton($url, $ajaxSubmitButtonId) {
    echo CHtml::ajaxSubmitButton('Save', $url, array(
        'error' => 'js:function(jqXHR, textStatus, errorThrown){
			alert(errorThrown);
			alert("There is some problem to save data");
}',
        'beforeSend' => 'js:function(){
			//     alert(\'beforeSend\');
}',
        'success' => "js:function(data, textStatus, jqXHR){
			//alert(data);
			var e = jQuery.parseJSON(data);
			// alert(e.restaurant_id)
			if(!e.success){
			var error='<ul>';
			jQuery.each(e, function(key, value) {
			error+='<li>'+value+'</li>';
})
			error+='</ul>';

			$('.errorSummary').html(error);
			$('.errorSummary').show();
}else{
			if(e.action == 'create'){
			$('#restaurant-form').attr('action','" . yii::app()->createUrl('restaurant/update') . "/'+e.restaurant_id);
			window.location.href = '" . yii::app()->createUrl('restaurant/update') . "/'+e.restaurant_id;

}
			if(e.action == 'update'){

			// window.location.href = '" . yii::app()->createUrl('restaurant/update') . "/'+e.restaurant_id;
                            var delay = 5000;
         setTimeout(function() {
     window.location.href = '" . yii::app()->createUrl('restaurant/update') . "/'+e.restaurant_id;
}, delay);

}
			if(e.action == 'profile'){
                        //5000 is the number of milliseconds (or 5 seconds) that you want to wait before redirection.
   var delay = 5000;
         setTimeout(function() {
    window.location.href = '" . yii::app()->createUrl('restaurant/profile') . "';
}, delay);
			//  window.location.href = '" . yii::app()->createUrl('restaurant/profile') . "';

}


			$('.errorSummary').hide();
			$('.errorMessage').hide();
			$('#statusMsg').html(e.msg).show();
			$('#statusMsg').fadeOut(10000);

}

}",
        'complete' => 'js:function(){
			//    alert(\'complete\');
}',
            //'update'=>'#where_to_put_the_response',
            ), array('id' => $ajaxSubmitButtonId . uniqid(), "name" => $ajaxSubmitButtonId . uniqid())
    );
}

function findAdminAllMarkets($markets, $res, $restaurant) {

    //pr($restaurant);
    if (!empty($markets)) {
        foreach ($markets as $marketKey => $market) {
            echo '<div class="market" id= "market' . $market["id"] . '" style="float:left:width: 603px;">';
            echo CHtml::checkBox('markets[]', FALSE, array('class' => 'marketcheckbox nouniform', 'onclick' => 'market(this)', 'value' => $market["id"], 'style' => '', 'id' => 'marketcheckbox' . $market['id'], 'ajax' => array(/* add your code */),
                'return' => true // add return like this
            ));
            echo '<span class="market_name">' . $market->market_name . '</span>';
            echo findAdminAllNeighbourHood($market['id'], $res, $restaurant);
            echo '</div>';
            // echo '<br/>';
        }
    }
}

function findAdminAllNeighbourHood($marketId, $res, $restaurant) {
    $neighbourHoods = array();
    $neighbourHoods = Neighborhood::model()->findAll('market_id=:market_id', array(':market_id' => $marketId));
    if (!empty($neighbourHoods)) {
        foreach ($neighbourHoods as $neighbourHoodsKey => $neighbourHood) {
            echo '<div  class="neighbourhood" id= "neighbourhood' . $neighbourHood["id"] . '" style="padding-left:30px;clear:both;">';
            echo CHtml::checkBox('neighbouhood[]', FALSE, array('class' => 'neighbouhoodcheckbox nouniform' . $neighbourHood['id'], 'value' => $neighbourHood["id"], 'onclick' => 'neighbourhood(this)', 'style' => '', 'id' => 'neighbourhoodcheckbox' . $neighbourHood['id'], 'ajax' => array(/* add your code */),
                'return' => true // add return like this
            ));
            echo '<span class="neighbouhood_name">' . $neighbourHood->neighborhood_name . '</span>' . '<br/>';
            echo '<div style="padding-left:30px;clear:both;">';
            echo findAdminAllRestaurant($neighbourHood['id'], $marketId, $res, $restaurant);
            echo '</div>';
            echo '</div>';
        }
    } else {
        echo '<span class="neighbouhood_blank"> </span>';
    }
}

function findAdminAllRestaurant($neighbourHoodId, $marketId, $res, $restaurantadmins) {
    $resId = array();
    $restaurants = array();
    if (!empty($restaurantadmins)) {
        foreach ($restaurantadmins as $key => $restaurantadmin) {
            $resId[] = $restaurantadmin->restaurant_id;
        }
        $ids = implode(',', $resId);
        $restaurants = Restaurant::model()->findAll('neighborhood_id=:neighborhood_id AND is_active=1 AND id IN(' . $ids . ')', array(':neighborhood_id' => $neighbourHoodId));
    }


    //pr($restaurants,false);;
    // $result=$model->findAllByAttributes(array('UserId'=>array(6,7,8,9)));
    if (!empty($restaurants)) {

        foreach ($restaurants as $restaurantKey => $restaurant) {

            //            $resId = array();
            //            foreach ($restaurantadmins as $key => $restaurantadmin) {
            //                $resId[] = $restaurantadmin->restaurant_id;
            //            }
            if (in_array($restaurant['id'], $res)) {
                $select = TRUE;
            } else {
                $select = FALSE;
            }
            // if (in_array($restaurant['id'], $resId)) {

            echo CHtml::checkBox('restaurant[' . $marketId . '][]', $select, array('class' => 'restaurantcheckbox nouniform' . $restaurant['id'], 'style' => '', 'value' => $restaurant["id"], 'id' => 'restaurantcheckbox' . $restaurant['id'], 'ajax' => array(/* add your code */),
                'return' => true // add return like this
            ));
            echo '<span class="restaurant_name">' . $restaurant->name . '</span>' . '<br/>';
            //  }
        }
    } else {
        echo '<span class="restaurant_blank"> </span>';
    }
}

function ajaxLoaderImage($obj) {
    $obj->beginWidget('zii.widgets.jui.CJuiDialog', array(
        'id' => 'ajaxdialog',
        // additional javascript options for the dialog plugin
        //  'htmlOptions'=>array('style'=>'border: 2px solid #000000;'),
        'options' => array(
            'title' => 'Please Wait...',
            'modal' => 'true',
            'width' => 400,
            'height' => 150,
            'autoOpen' => false,
            'resizable' => false,
        ),
    ));
    echo '<div id="tabLoader" ></div>';

    $obj->endWidget('zii.widgets.jui.CJuiDialog');
}

function setWaitTimeToDisable() {
    $currentDay = date('l');
    $is_disabled = 0;

    if ($currentDay != 'Sunday') {
        $sundyTime = strtotime('last sunday 9:30 PM');
    } elseif ($currentDay == 'Sunday') {
        $sundyTime = strtotime('today 9:30 PM');
    }

    if ($currentDay == 'Saturday') {
        $fridayTime = strtotime('last friday 4:30 PM');
    } elseif ($currentDay == 'Friday') {
        $fridayTime = strtotime('today 4:30 PM');
    } else {
        $fridayTime = strtotime('friday 4:30 PM');
    }

    $currentTime = strtotime('NOW');


    if ($currentTime >= $sundyTime && $currentTime <= $fridayTime) {
        $is_disabled = 1;
    }

    return $is_disabled;
}

function displayNotEmptyValue($value, $defaltValue = '') {
    return $value = empty($value) ? $defaltValue : $value;
}

function getCreditCardTypes() {
    return array(
        'Master Card' => 'Master Card', 'Visa' => 'Visa',
        'Discover' => 'Discover', 'American Express' => 'American Express'
    );
}

function findAllMarkets($markets, $res) {


    foreach ($markets as $marketKey => $market) {
        echo '<div class="market" id= "market' . $market["id"] . '" style="float:left:width: 603px;">';
        echo CHtml::checkBox('markets[]', FALSE, array('class' => 'marketcheckbox nouniform', 'onclick' => 'market(this)', 'value' => $market["id"], 'style' => '', 'id' => 'marketcheckbox' . $market['id'], 'ajax' => array(/* add your code */),
            'return' => true // add return like this
        ));
        echo '<span class="market_name">' . $market->market_name . '</span>';
        echo findAllNeighbourHood($market['id'], $res);
        echo '</div>';
        // echo '<br/>';
    }
}

function findAllNeighbourHood($marketId, $res) {
    $neighbourHoods = array();
    $neighbourHoods = Neighborhood::model()->findAll('market_id=:market_id', array(':market_id' => $marketId));
    if (!empty($neighbourHoods)) {
        foreach ($neighbourHoods as $neighbourHoodsKey => $neighbourHood) {
            echo '<div  class="neighbourhood" id= "neighbourhood' . $neighbourHood["id"] . '" style="padding-left:30px;clear:both;">';
            echo CHtml::checkBox('neighbouhood[]', FALSE, array('class' => 'neighbouhoodcheckbox nouniform' . $neighbourHood['id'], 'value' => $neighbourHood["id"], 'onclick' => 'neighbourhood(this)', 'style' => '', 'id' => 'neighbourhoodcheckbox' . $neighbourHood['id'], 'ajax' => array(/* add your code */),
                'return' => true // add return like this
            ));
            echo '<span class="neighbouhood_name">' . $neighbourHood->neighborhood_name . '</span>' . '<br/>';
            // echo $neighbourHood->neighborhood_name . '<br/>';
            echo '<div style="padding-left:30px;clear:both;">';


            echo findAllRestaurant($neighbourHood['id'], $marketId, $res);

            echo '</div>';
            echo '</div>';
        }
    } else {
        echo '<span class="neighbouhood_blank"></span>';
    }
}

function findAllRestaurant($neighbourHoodId, $marketId, $res) {
    $restaurants = array();
    $restaurants = Restaurant::model()->findAll('neighborhood_id=:neighborhood_id AND is_active=1', array(':neighborhood_id' => $neighbourHoodId));
    if (!empty($restaurants)) {
        foreach ($restaurants as $restaurantKey => $restaurant) {
            if (in_array($restaurant['id'], $res)) {
                $select = TRUE;
            } else {
                $select = FALSE;
            }
            echo CHtml::checkBox('restaurant[' . $marketId . '][]', $select, array('class' => 'restaurantcheckbox nouniform' . $restaurant['id'], 'style' => '', 'value' => $restaurant["id"], 'id' => 'restaurantcheckbox' . $restaurant['id'], 'ajax' => array(/* add your code */),
                'return' => true // add return like this
            ));
            echo '<span class="restaurant_name">' . $restaurant->name . '</span>' . '<br/>';
        }
    } else {
        echo '<span class="restaurant_blank"></span>';
    }
}

function getOffSetForPaging($pageCount, $pageSize) {
    if (!empty($pageCount) && !empty($pageSize)) {
        $start = ($pageCount - 1) * $pageSize;
        $end = ($pageCount * $pageSize) - 1;
        return array('start' => $start, 'end' => $end);
    }
}

function getUserFavoriteRestaurant($user_id) {

    $restaurantsIds = Yii::app()->db
            ->createCommand()
            ->select('restaurant_id')
            ->from('user_favorite_restaurant')
            ->where('user_id=:user_id', array(':user_id' => $user_id))
            ->queryAll();


    return $restaurantsIds;
}

function getUserFavoriteRestaurantStr($user_id) {
    $restaurantsIds = getUserFavoriteRestaurant($user_id);
    $restaurantsIdsStr = '';
    if (!empty($restaurantsIds) && is_array($restaurantsIds)) {
        $restaurantsIdsStr = multiDimensionalImplode(',', $restaurantsIds);
    }
    return $restaurantsIdsStr;
}

//function GetDays($sStartDate, $sEndDate, $startDays) {
//    $year = date("Y", strtotime($sStartDate));
//    $month = date("m", strtotime($sStartDate));
//    $days = date("d", strtotime($sStartDate));
//    if ($startDays > $days) {
//        $sStartDate = $year . '-' . ($month + 1) . '-' . $days;
//    } else {
//        $sStartDate = $year . '-' . ($month) . '-' . $days;
//    }
//
//    $sStartDate = gmdate("Y-m-d", strtotime($sStartDate));
//
//    $sEndDate = gmdate("Y-m-d", strtotime($sEndDate));
//
//    $aDays[] = $sStartDate;
//
//    $sCurrentDate = $sStartDate;
//
//    // While the current date is less than the end date
//    while ($sCurrentDate < $sEndDate) {
//        // Add a day to the current date
//        $sCurrentDate = gmdate("Y-m-d", strtotime("+1 month", strtotime($sCurrentDate)));
//
//        // Add this new day to the aDays array
//        $aDays[] = $sCurrentDate;
//    }
//
//    // Once the loop has finished, return the
//    // array of days.
//    return $aDays;
//}
function GetDays($sStartDate, $sEndDate, $startDays) {
    $years = date("Y", strtotime($sStartDate));
    $months = date("m", strtotime($sStartDate));
    $dates = date("d", strtotime($sStartDate));
    //echo $dates;
    if ($startDays > $dates) {
        $sStartDate = $years . '-' . $months . '-' . $startDays;
        $sStartDate = date("Y-m-d", strtotime($sStartDate));
    } else {
        $sStartDate = $years . '-' . ($months) . '-' . $startDays;
        $sStartDate = date("Y-m-d", strtotime("+1 month", strtotime($sStartDate)));
    }

    $sEndDate = date("Y-m-d", strtotime("-1 month", strtotime($sEndDate)));

    // Start the variable off with the start date
    $aDays[] = $sStartDate;


    $sCurrentDate = $sStartDate;


    while ($sCurrentDate <= $sEndDate) {

        $sCurrentDate = date("Y-m-d", strtotime("+1 month", strtotime($sCurrentDate)));

        // Add this new day to the aDays array
        $aDays[] = $sCurrentDate;
    }

    // Once the loop has finished, return the
    // array of days.
    return $aDays;
}

function getDaysFromDateRange($weekDay, $startDate, $endDate) {
    $start = new DateTime($startDate);
    $end = new DateTime($endDate);
    $dates = array();
    while ($start <= $end) {
        $start->modify('+1 day');
        if (strtolower($start->format('l')) == strtolower($weekDay)) {
            $dates[] = $start->format('Y-m-d');
        }
    }
    return $dates;
}

/**
 * function change time to a given time zone
 *
 */
function calculateTimeByTimeZone($zone, $dateTime, $formate = 'Y-m-d H:i:s') {
    $date = new DateTime($dateTime, new DateTimeZone($zone));
    $serverTimeZone = date_default_timezone_get();
    $date->setTimezone(new DateTimeZone($serverTimeZone));
    return $date->format($formate);
}

function timezoneOffset($zone) {
    //$dateTime, $formate='Y-m-d H:i:s'
    //$utcdate = new DateTime(time(), new DateTimeZone('UTC'));
    $tzdate = new DateTime(time(), new DateTimeZone('UTC'));
    $tzdate->setTimezone(new DateTimeZone($zone));
    return $tzdate->getOffset();
}

function calculateSecondsFromUTC($zone) {
    $cdate = date('Y-m-d H:i:s');
    $UTC = new DateTimeZone("UTC");
    $newTZ = new DateTimeZone($zone);
    $date = new DateTime($cdate, $UTC);
    $date->setTimezone($newTZ);
    $date->format('Y-m-d H:i:s');
    return $date->getOffset();
}

function getAllDataByTable($table, $attributes = array('id'), string $condationStr = null, array $condationArr = null, $limit = null, $orderColName = null) {
    $data = array();
    if (is_array($attributes)) {
        $attributesStr = implode(',', $attributes);
    } elseif (is_string($attributes)) {
        $attributesStr = $attributes;
    }

    $rest = Yii::app()->db->createCommand()
            ->select($attributesStr)
            ->from($table);

    if (!empty($condationStr) && !empty($condationArr))
        $rest->where($condationStr, $condationArr);

    if (!is_null($orderColName))
        $rest->order($orderColName);

    if ($limit != null && $limit == 1)
        $data = $rest->queryRow();
    else
        $data = $rest->queryAll();

    return $data;
}

function getHappyHourTimingByDOW($odw, $tz, $time) {
    $date = $odw + 2;
    $date = sprintf("%02s", $date);
    $date = '1970-01-' . $date;

    $dt = new DateTime($date);
}

?>
